home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pydoc.py < prev    next >
Text File  |  2009-11-02  |  93KB  |  2,341 lines

  1. #! /usr/bin/python2.6
  2. # -*- coding: latin-1 -*-
  3. """Generate Python documentation in HTML or text for interactive use.
  4.  
  5. In the Python interpreter, do "from pydoc import help" to provide online
  6. help.  Calling help(thing) on a Python object documents the object.
  7.  
  8. Or, at the shell command line outside of Python:
  9.  
  10. Run "pydoc <name>" to show documentation on something.  <name> may be
  11. the name of a function, module, package, or a dotted reference to a
  12. class or function within a module or module in a package.  If the
  13. argument contains a path segment delimiter (e.g. slash on Unix,
  14. backslash on Windows) it is treated as the path to a Python source file.
  15.  
  16. Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
  17. of all available modules.
  18.  
  19. Run "pydoc -p <port>" to start an HTTP server on a given port on the
  20. local machine to generate documentation web pages.
  21.  
  22. For platforms without a command line, "pydoc -g" starts the HTTP server
  23. and also pops up a little window for controlling it.
  24.  
  25. Run "pydoc -w <name>" to write out the HTML documentation for a module
  26. to a file named "<name>.html".
  27.  
  28. Module docs for core modules are assumed to be in
  29.  
  30.     /usr/share/doc/pythonX.Y/html/library
  31.  
  32. if the pythonX.Y-doc package is installed or in
  33.  
  34.     http://docs.python.org/library/
  35.  
  36. This can be overridden by setting the PYTHONDOCS environment variable
  37. to a different URL or to a local directory containing the Library
  38. Reference Manual pages.
  39. """
  40.  
  41. __author__ = "Ka-Ping Yee <ping@lfw.org>"
  42. __date__ = "26 February 2001"
  43.  
  44. __version__ = "$Revision: 73530 $"
  45. __credits__ = """Guido van Rossum, for an excellent programming language.
  46. Tommy Burnette, the original creator of manpy.
  47. Paul Prescod, for all his work on onlinehelp.
  48. Richard Chamberlain, for the first implementation of textdoc.
  49. """
  50.  
  51. # Known bugs that can't be fixed here:
  52. #   - imp.load_module() cannot be prevented from clobbering existing
  53. #     loaded modules, so calling synopsis() on a binary module file
  54. #     changes the contents of any existing module with the same name.
  55. #   - If the __file__ attribute on a module is a relative path and
  56. #     the current directory is changed with os.chdir(), an incorrect
  57. #     path will be displayed.
  58.  
  59. import sys, imp, os, re, types, inspect, __builtin__, pkgutil
  60. from repr import Repr
  61. from string import expandtabs, find, join, lower, split, strip, rfind, rstrip
  62. from traceback import extract_tb
  63. try:
  64.     from collections import deque
  65. except ImportError:
  66.     # Python 2.3 compatibility
  67.     class deque(list):
  68.         def popleft(self):
  69.             return self.pop(0)
  70.  
  71. # --------------------------------------------------------- common routines
  72.  
  73. def pathdirs():
  74.     """Convert sys.path into a list of absolute, existing, unique paths."""
  75.     dirs = []
  76.     normdirs = []
  77.     for dir in sys.path:
  78.         dir = os.path.abspath(dir or '.')
  79.         normdir = os.path.normcase(dir)
  80.         if normdir not in normdirs and os.path.isdir(dir):
  81.             dirs.append(dir)
  82.             normdirs.append(normdir)
  83.     return dirs
  84.  
  85. def getdoc(object):
  86.     """Get the doc string or comments for an object."""
  87.     result = inspect.getdoc(object) or inspect.getcomments(object)
  88.     return result and re.sub('^ *\n', '', rstrip(result)) or ''
  89.  
  90. def splitdoc(doc):
  91.     """Split a doc string into a synopsis line (if any) and the rest."""
  92.     lines = split(strip(doc), '\n')
  93.     if len(lines) == 1:
  94.         return lines[0], ''
  95.     elif len(lines) >= 2 and not rstrip(lines[1]):
  96.         return lines[0], join(lines[2:], '\n')
  97.     return '', join(lines, '\n')
  98.  
  99. def classname(object, modname):
  100.     """Get a class name and qualify it with a module name if necessary."""
  101.     name = object.__name__
  102.     if object.__module__ != modname:
  103.         name = object.__module__ + '.' + name
  104.     return name
  105.  
  106. def isdata(object):
  107.     """Check if an object is of a type that probably means it's data."""
  108.     return not (inspect.ismodule(object) or inspect.isclass(object) or
  109.                 inspect.isroutine(object) or inspect.isframe(object) or
  110.                 inspect.istraceback(object) or inspect.iscode(object))
  111.  
  112. def replace(text, *pairs):
  113.     """Do a series of global replacements on a string."""
  114.     while pairs:
  115.         text = join(split(text, pairs[0]), pairs[1])
  116.         pairs = pairs[2:]
  117.     return text
  118.  
  119. def cram(text, maxlen):
  120.     """Omit part of a string if needed to make it fit in a maximum length."""
  121.     if len(text) > maxlen:
  122.         pre = max(0, (maxlen-3)//2)
  123.         post = max(0, maxlen-3-pre)
  124.         return text[:pre] + '...' + text[len(text)-post:]
  125.     return text
  126.  
  127. _re_stripid = re.compile(r' at 0x[0-9a-f]{6,16}(>+)$', re.IGNORECASE)
  128. def stripid(text):
  129.     """Remove the hexadecimal id from a Python object representation."""
  130.     # The behaviour of %p is implementation-dependent in terms of case.
  131.     if _re_stripid.search(repr(Exception)):
  132.         return _re_stripid.sub(r'\1', text)
  133.     return text
  134.  
  135. def _is_some_method(obj):
  136.     return inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)
  137.  
  138. def allmethods(cl):
  139.     methods = {}
  140.     for key, value in inspect.getmembers(cl, _is_some_method):
  141.         methods[key] = 1
  142.     for base in cl.__bases__:
  143.         methods.update(allmethods(base)) # all your base are belong to us
  144.     for key in methods.keys():
  145.         methods[key] = getattr(cl, key)
  146.     return methods
  147.  
  148. def _split_list(s, predicate):
  149.     """Split sequence s via predicate, and return pair ([true], [false]).
  150.  
  151.     The return value is a 2-tuple of lists,
  152.         ([x for x in s if predicate(x)],
  153.          [x for x in s if not predicate(x)])
  154.     """
  155.  
  156.     yes = []
  157.     no = []
  158.     for x in s:
  159.         if predicate(x):
  160.             yes.append(x)
  161.         else:
  162.             no.append(x)
  163.     return yes, no
  164.  
  165. def visiblename(name, all=None):
  166.     """Decide whether to show documentation on a variable."""
  167.     # Certain special names are redundant.
  168.     _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__',
  169.                      '__module__', '__name__', '__slots__', '__package__')
  170.     if name in _hidden_names: return 0
  171.     # Private names are hidden, but special names are displayed.
  172.     if name.startswith('__') and name.endswith('__'): return 1
  173.     if all is not None:
  174.         # only document that which the programmer exported in __all__
  175.         return name in all
  176.     else:
  177.         return not name.startswith('_')
  178.  
  179. def classify_class_attrs(object):
  180.     """Wrap inspect.classify_class_attrs, with fixup for data descriptors."""
  181.     def fixup(data):
  182.         name, kind, cls, value = data
  183.         if inspect.isdatadescriptor(value):
  184.             kind = 'data descriptor'
  185.         return name, kind, cls, value
  186.     return map(fixup, inspect.classify_class_attrs(object))
  187.  
  188. # ----------------------------------------------------- module manipulation
  189.  
  190. def ispackage(path):
  191.     """Guess whether a path refers to a package directory."""
  192.     if os.path.isdir(path):
  193.         for ext in ('.py', '.pyc', '.pyo'):
  194.             if os.path.isfile(os.path.join(path, '__init__' + ext)):
  195.                 return True
  196.     return False
  197.  
  198. def source_synopsis(file):
  199.     line = file.readline()
  200.     while line[:1] == '#' or not strip(line):
  201.         line = file.readline()
  202.         if not line: break
  203.     line = strip(line)
  204.     if line[:4] == 'r"""': line = line[1:]
  205.     if line[:3] == '"""':
  206.         line = line[3:]
  207.         if line[-1:] == '\\': line = line[:-1]
  208.         while not strip(line):
  209.             line = file.readline()
  210.             if not line: break
  211.         result = strip(split(line, '"""')[0])
  212.     else: result = None
  213.     return result
  214.  
  215. def synopsis(filename, cache={}):
  216.     """Get the one-line summary out of a module file."""
  217.     mtime = os.stat(filename).st_mtime
  218.     lastupdate, result = cache.get(filename, (0, None))
  219.     if lastupdate < mtime:
  220.         info = inspect.getmoduleinfo(filename)
  221.         try:
  222.             file = open(filename)
  223.         except IOError:
  224.             # module can't be opened, so skip it
  225.             return None
  226.         if info and 'b' in info[2]: # binary modules have to be imported
  227.             try: module = imp.load_module('__temp__', file, filename, info[1:])
  228.             except: return None
  229.             result = (module.__doc__ or '').splitlines()[0]
  230.             del sys.modules['__temp__']
  231.         else: # text modules can be directly examined
  232.             result = source_synopsis(file)
  233.             file.close()
  234.         cache[filename] = (mtime, result)
  235.     return result
  236.  
  237. class ErrorDuringImport(Exception):
  238.     """Errors that occurred while trying to import something to document it."""
  239.     def __init__(self, filename, exc_info):
  240.         exc, value, tb = exc_info
  241.         self.filename = filename
  242.         self.exc = exc
  243.         self.value = value
  244.         self.tb = tb
  245.  
  246.     def __str__(self):
  247.         exc = self.exc
  248.         if type(exc) is types.ClassType:
  249.             exc = exc.__name__
  250.         return 'problem in %s - %s: %s' % (self.filename, exc, self.value)
  251.  
  252. def importfile(path):
  253.     """Import a Python source file or compiled file given its path."""
  254.     magic = imp.get_magic()
  255.     file = open(path, 'r')
  256.     if file.read(len(magic)) == magic:
  257.         kind = imp.PY_COMPILED
  258.     else:
  259.         kind = imp.PY_SOURCE
  260.     file.close()
  261.     filename = os.path.basename(path)
  262.     name, ext = os.path.splitext(filename)
  263.     file = open(path, 'r')
  264.     try:
  265.         module = imp.load_module(name, file, path, (ext, 'r', kind))
  266.     except:
  267.         raise ErrorDuringImport(path, sys.exc_info())
  268.     file.close()
  269.     return module
  270.  
  271. def safeimport(path, forceload=0, cache={}):
  272.     """Import a module; handle errors; return None if the module isn't found.
  273.  
  274.     If the module *is* found but an exception occurs, it's wrapped in an
  275.     ErrorDuringImport exception and reraised.  Unlike __import__, if a
  276.     package path is specified, the module at the end of the path is returned,
  277.     not the package at the beginning.  If the optional 'forceload' argument
  278.     is 1, we reload the module from disk (unless it's a dynamic extension)."""
  279.     try:
  280.         # If forceload is 1 and the module has been previously loaded from
  281.         # disk, we always have to reload the module.  Checking the file's
  282.         # mtime isn't good enough (e.g. the module could contain a class
  283.         # that inherits from another module that has changed).
  284.         if forceload and path in sys.modules:
  285.             if path not in sys.builtin_module_names:
  286.                 # Avoid simply calling reload() because it leaves names in
  287.                 # the currently loaded module lying around if they're not
  288.                 # defined in the new source file.  Instead, remove the
  289.                 # module from sys.modules and re-import.  Also remove any
  290.                 # submodules because they won't appear in the newly loaded
  291.                 # module's namespace if they're already in sys.modules.
  292.                 subs = [m for m in sys.modules if m.startswith(path + '.')]
  293.                 for key in [path] + subs:
  294.                     # Prevent garbage collection.
  295.                     cache[key] = sys.modules[key]
  296.                     del sys.modules[key]
  297.         module = __import__(path)
  298.     except:
  299.         # Did the error occur before or after the module was found?
  300.         (exc, value, tb) = info = sys.exc_info()
  301.         if path in sys.modules:
  302.             # An error occurred while executing the imported module.
  303.             raise ErrorDuringImport(sys.modules[path].__file__, info)
  304.         elif exc is SyntaxError:
  305.             # A SyntaxError occurred before we could execute the module.
  306.             raise ErrorDuringImport(value.filename, info)
  307.         elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport':
  308.             # The import error occurred directly in this function,
  309.             # which means there is no such module in the path.
  310.             return None
  311.         else:
  312.             # Some other error occurred during the importing process.
  313.             raise ErrorDuringImport(path, sys.exc_info())
  314.     for part in split(path, '.')[1:]:
  315.         try: module = getattr(module, part)
  316.         except AttributeError: return None
  317.     return module
  318.  
  319. # ---------------------------------------------------- formatter base class
  320.  
  321. class Doc:
  322.     def document(self, object, name=None, *args):
  323.         """Generate documentation for an object."""
  324.         args = (object, name) + args
  325.         # 'try' clause is to attempt to handle the possibility that inspect
  326.         # identifies something in a way that pydoc itself has issues handling;
  327.         # think 'super' and how it is a descriptor (which raises the exception
  328.         # by lacking a __name__ attribute) and an instance.
  329.         if inspect.isgetsetdescriptor(object): return self.docdata(*args)
  330.         if inspect.ismemberdescriptor(object): return self.docdata(*args)
  331.         try:
  332.             if inspect.ismodule(object): return self.docmodule(*args)
  333.             if inspect.isclass(object): return self.docclass(*args)
  334.             if inspect.isroutine(object): return self.docroutine(*args)
  335.         except AttributeError:
  336.             pass
  337.         if isinstance(object, property): return self.docproperty(*args)
  338.         return self.docother(*args)
  339.  
  340.     def fail(self, object, name=None, *args):
  341.         """Raise an exception for unimplemented types."""
  342.         message = "don't know how to document object%s of type %s" % (
  343.             name and ' ' + repr(name), type(object).__name__)
  344.         raise TypeError, message
  345.  
  346.     docmodule = docclass = docroutine = docother = docproperty = docdata = fail
  347.  
  348.     def getdocloc(self, object):
  349.         """Return the location of module docs or None"""
  350.  
  351.         try:
  352.             file = inspect.getabsfile(object)
  353.         except TypeError:
  354.             file = '(built-in)'
  355.  
  356.         docloc = os.environ.get("PYTHONDOCS",
  357.                                 "http://docs.python.org/library")
  358.         docdir = '/usr/share/doc/python%s/html/library' % sys.version[:3]
  359.         if not os.environ.has_key("PYTHONDOCS") and os.path.isdir(docdir):
  360.             docloc = docdir
  361.         basedir = os.path.join(sys.exec_prefix, "lib",
  362.                                "python"+sys.version[0:3])
  363.         if (isinstance(object, type(os)) and
  364.             (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
  365.                                  'marshal', 'posix', 'signal', 'sys',
  366.                                  'thread', 'zipimport') or
  367.              (file.startswith(basedir) and
  368.               not file.startswith(os.path.join(basedir, 'site-packages'))))):
  369.             if docloc.startswith("http://"):
  370.                 docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
  371.             else:
  372.                 docloc = os.path.join(docloc, object.__name__ + ".html")
  373.         else:
  374.             docloc = None
  375.         return docloc
  376.  
  377. # -------------------------------------------- HTML documentation generator
  378.  
  379. class HTMLRepr(Repr):
  380.     """Class for safely making an HTML representation of a Python object."""
  381.     def __init__(self):
  382.         Repr.__init__(self)
  383.         self.maxlist = self.maxtuple = 20
  384.         self.maxdict = 10
  385.         self.maxstring = self.maxother = 100
  386.  
  387.     def escape(self, text):
  388.         return replace(text, '&', '&', '<', '<', '>', '>')
  389.  
  390.     def repr(self, object):
  391.         return Repr.repr(self, object)
  392.  
  393.     def repr1(self, x, level):
  394.         if hasattr(type(x), '__name__'):
  395.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  396.             if hasattr(self, methodname):
  397.                 return getattr(self, methodname)(x, level)
  398.         return self.escape(cram(stripid(repr(x)), self.maxother))
  399.  
  400.     def repr_string(self, x, level):
  401.         test = cram(x, self.maxstring)
  402.         testrepr = repr(test)
  403.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  404.             # Backslashes are only literal in the string and are never
  405.             # needed to make any special characters, so show a raw string.
  406.             return 'r' + testrepr[0] + self.escape(test) + testrepr[0]
  407.         return re.sub(r'((\\[\\abfnrtv\'"]|\\[0-9]..|\\x..|\\u....)+)',
  408.                       r'<font color="#c040c0">\1</font>',
  409.                       self.escape(testrepr))
  410.  
  411.     repr_str = repr_string
  412.  
  413.     def repr_instance(self, x, level):
  414.         try:
  415.             return self.escape(cram(stripid(repr(x)), self.maxstring))
  416.         except:
  417.             return self.escape('<%s instance>' % x.__class__.__name__)
  418.  
  419.     repr_unicode = repr_string
  420.  
  421. class HTMLDoc(Doc):
  422.     """Formatter class for HTML documentation."""
  423.  
  424.     # ------------------------------------------- HTML formatting utilities
  425.  
  426.     _repr_instance = HTMLRepr()
  427.     repr = _repr_instance.repr
  428.     escape = _repr_instance.escape
  429.  
  430.     def page(self, title, contents):
  431.         """Format an HTML page."""
  432.         return '''
  433. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  434. <html><head><title>Python: %s</title>
  435. </head><body bgcolor="#f0f0f8">
  436. %s
  437. </body></html>''' % (title, contents)
  438.  
  439.     def heading(self, title, fgcol, bgcol, extras=''):
  440.         """Format a page heading."""
  441.         return '''
  442. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="heading">
  443. <tr bgcolor="%s">
  444. <td valign=bottom> <br>
  445. <font color="%s" face="helvetica, arial"> <br>%s</font></td
  446. ><td align=right valign=bottom
  447. ><font color="%s" face="helvetica, arial">%s</font></td></tr></table>
  448.     ''' % (bgcol, fgcol, title, fgcol, extras or ' ')
  449.  
  450.     def section(self, title, fgcol, bgcol, contents, width=6,
  451.                 prelude='', marginalia=None, gap=' '):
  452.         """Format a section with a heading."""
  453.         if marginalia is None:
  454.             marginalia = '<tt>' + ' ' * width + '</tt>'
  455.         result = '''<p>
  456. <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
  457. <tr bgcolor="%s">
  458. <td colspan=3 valign=bottom> <br>
  459. <font color="%s" face="helvetica, arial">%s</font></td></tr>
  460.     ''' % (bgcol, fgcol, title)
  461.         if prelude:
  462.             result = result + '''
  463. <tr bgcolor="%s"><td rowspan=2>%s</td>
  464. <td colspan=2>%s</td></tr>
  465. <tr><td>%s</td>''' % (bgcol, marginalia, prelude, gap)
  466.         else:
  467.             result = result + '''
  468. <tr><td bgcolor="%s">%s</td><td>%s</td>''' % (bgcol, marginalia, gap)
  469.  
  470.         return result + '\n<td width="100%%">%s</td></tr></table>' % contents
  471.  
  472.     def bigsection(self, title, *args):
  473.         """Format a section with a big heading."""
  474.         title = '<big><strong>%s</strong></big>' % title
  475.         return self.section(title, *args)
  476.  
  477.     def preformat(self, text):
  478.         """Format literal preformatted text."""
  479.         text = self.escape(expandtabs(text))
  480.         return replace(text, '\n\n', '\n \n', '\n\n', '\n \n',
  481.                              ' ', ' ', '\n', '<br>\n')
  482.  
  483.     def multicolumn(self, list, format, cols=4):
  484.         """Format a list of items into a multi-column list."""
  485.         result = ''
  486.         rows = (len(list)+cols-1)/cols
  487.         for col in range(cols):
  488.             result = result + '<td width="%d%%" valign=top>' % (100/cols)
  489.             for i in range(rows*col, rows*col+rows):
  490.                 if i < len(list):
  491.                     result = result + format(list[i]) + '<br>\n'
  492.             result = result + '</td>'
  493.         return '<table width="100%%" summary="list"><tr>%s</tr></table>' % result
  494.  
  495.     def grey(self, text): return '<font color="#909090">%s</font>' % text
  496.  
  497.     def namelink(self, name, *dicts):
  498.         """Make a link for an identifier, given name-to-URL mappings."""
  499.         for dict in dicts:
  500.             if name in dict:
  501.                 return '<a href="%s">%s</a>' % (dict[name], name)
  502.         return name
  503.  
  504.     def classlink(self, object, modname):
  505.         """Make a link for a class."""
  506.         name, module = object.__name__, sys.modules.get(object.__module__)
  507.         if hasattr(module, name) and getattr(module, name) is object:
  508.             return '<a href="%s.html#%s">%s</a>' % (
  509.                 module.__name__, name, classname(object, modname))
  510.         return classname(object, modname)
  511.  
  512.     def modulelink(self, object):
  513.         """Make a link for a module."""
  514.         return '<a href="%s.html">%s</a>' % (object.__name__, object.__name__)
  515.  
  516.     def modpkglink(self, data):
  517.         """Make a link for a module or package to display in an index."""
  518.         name, path, ispackage, shadowed = data
  519.         if shadowed:
  520.             return self.grey(name)
  521.         if path:
  522.             url = '%s.%s.html' % (path, name)
  523.         else:
  524.             url = '%s.html' % name
  525.         if ispackage:
  526.             text = '<strong>%s</strong> (package)' % name
  527.         else:
  528.             text = name
  529.         return '<a href="%s">%s</a>' % (url, text)
  530.  
  531.     def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
  532.         """Mark up some plain text, given a context of symbols to look for.
  533.         Each context dictionary maps object names to anchor names."""
  534.         escape = escape or self.escape
  535.         results = []
  536.         here = 0
  537.         pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
  538.                                 r'RFC[- ]?(\d+)|'
  539.                                 r'PEP[- ]?(\d+)|'
  540.                                 r'(self\.)?(\w+))')
  541.         while True:
  542.             match = pattern.search(text, here)
  543.             if not match: break
  544.             start, end = match.span()
  545.             results.append(escape(text[here:start]))
  546.  
  547.             all, scheme, rfc, pep, selfdot, name = match.groups()
  548.             if scheme:
  549.                 url = escape(all).replace('"', '"')
  550.                 results.append('<a href="%s">%s</a>' % (url, url))
  551.             elif rfc:
  552.                 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
  553.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  554.             elif pep:
  555.                 url = 'http://www.python.org/dev/peps/pep-%04d/' % int(pep)
  556.                 results.append('<a href="%s">%s</a>' % (url, escape(all)))
  557.             elif text[end:end+1] == '(':
  558.                 results.append(self.namelink(name, methods, funcs, classes))
  559.             elif selfdot:
  560.                 results.append('self.<strong>%s</strong>' % name)
  561.             else:
  562.                 results.append(self.namelink(name, classes))
  563.             here = end
  564.         results.append(escape(text[here:]))
  565.         return join(results, '')
  566.  
  567.     # ---------------------------------------------- type-specific routines
  568.  
  569.     def formattree(self, tree, modname, parent=None):
  570.         """Produce HTML for a class tree as given by inspect.getclasstree()."""
  571.         result = ''
  572.         for entry in tree:
  573.             if type(entry) is type(()):
  574.                 c, bases = entry
  575.                 result = result + '<dt><font face="helvetica, arial">'
  576.                 result = result + self.classlink(c, modname)
  577.                 if bases and bases != (parent,):
  578.                     parents = []
  579.                     for base in bases:
  580.                         parents.append(self.classlink(base, modname))
  581.                     result = result + '(' + join(parents, ', ') + ')'
  582.                 result = result + '\n</font></dt>'
  583.             elif type(entry) is type([]):
  584.                 result = result + '<dd>\n%s</dd>\n' % self.formattree(
  585.                     entry, modname, c)
  586.         return '<dl>\n%s</dl>\n' % result
  587.  
  588.     def docmodule(self, object, name=None, mod=None, *ignored):
  589.         """Produce HTML documentation for a module object."""
  590.         name = object.__name__ # ignore the passed-in name
  591.         try:
  592.             all = object.__all__
  593.         except AttributeError:
  594.             all = None
  595.         parts = split(name, '.')
  596.         links = []
  597.         for i in range(len(parts)-1):
  598.             links.append(
  599.                 '<a href="%s.html"><font color="#ffffff">%s</font></a>' %
  600.                 (join(parts[:i+1], '.'), parts[i]))
  601.         linkedname = join(links + parts[-1:], '.')
  602.         head = '<big><big><strong>%s</strong></big></big>' % linkedname
  603.         try:
  604.             path = inspect.getabsfile(object)
  605.             url = path
  606.             if sys.platform == 'win32':
  607.                 import nturl2path
  608.                 url = nturl2path.pathname2url(path)
  609.             filelink = '<a href="file:%s">%s</a>' % (url, path)
  610.         except TypeError:
  611.             filelink = '(built-in)'
  612.         info = []
  613.         if hasattr(object, '__version__'):
  614.             version = str(object.__version__)
  615.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  616.                 version = strip(version[11:-1])
  617.             info.append('version %s' % self.escape(version))
  618.         if hasattr(object, '__date__'):
  619.             info.append(self.escape(str(object.__date__)))
  620.         if info:
  621.             head = head + ' (%s)' % join(info, ', ')
  622.         docloc = self.getdocloc(object)
  623.         if docloc is not None:
  624.             docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
  625.         else:
  626.             docloc = ''
  627.         result = self.heading(
  628.             head, '#ffffff', '#7799ee',
  629.             '<a href=".">index</a><br>' + filelink + docloc)
  630.  
  631.         modules = inspect.getmembers(object, inspect.ismodule)
  632.  
  633.         classes, cdict = [], {}
  634.         for key, value in inspect.getmembers(object, inspect.isclass):
  635.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  636.             if (all is not None or
  637.                 (inspect.getmodule(value) or object) is object):
  638.                 if visiblename(key, all):
  639.                     classes.append((key, value))
  640.                     cdict[key] = cdict[value] = '#' + key
  641.         for key, value in classes:
  642.             for base in value.__bases__:
  643.                 key, modname = base.__name__, base.__module__
  644.                 module = sys.modules.get(modname)
  645.                 if modname != name and module and hasattr(module, key):
  646.                     if getattr(module, key) is base:
  647.                         if not key in cdict:
  648.                             cdict[key] = cdict[base] = modname + '.html#' + key
  649.         funcs, fdict = [], {}
  650.         for key, value in inspect.getmembers(object, inspect.isroutine):
  651.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  652.             if (all is not None or
  653.                 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  654.                 if visiblename(key, all):
  655.                     funcs.append((key, value))
  656.                     fdict[key] = '#-' + key
  657.                     if inspect.isfunction(value): fdict[value] = fdict[key]
  658.         data = []
  659.         for key, value in inspect.getmembers(object, isdata):
  660.             if visiblename(key, all):
  661.                 data.append((key, value))
  662.  
  663.         doc = self.markup(getdoc(object), self.preformat, fdict, cdict)
  664.         doc = doc and '<tt>%s</tt>' % doc
  665.         result = result + '<p>%s</p>\n' % doc
  666.  
  667.         if hasattr(object, '__path__'):
  668.             modpkgs = []
  669.             for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  670.                 modpkgs.append((modname, name, ispkg, 0))
  671.             modpkgs.sort()
  672.             contents = self.multicolumn(modpkgs, self.modpkglink)
  673.             result = result + self.bigsection(
  674.                 'Package Contents', '#ffffff', '#aa55cc', contents)
  675.         elif modules:
  676.             contents = self.multicolumn(
  677.                 modules, lambda key_value, s=self: s.modulelink(key_value[1]))
  678.             result = result + self.bigsection(
  679.                 'Modules', '#ffffff', '#aa55cc', contents)
  680.  
  681.         if classes:
  682.             classlist = map(lambda key_value: key_value[1], classes)
  683.             contents = [
  684.                 self.formattree(inspect.getclasstree(classlist, 1), name)]
  685.             for key, value in classes:
  686.                 contents.append(self.document(value, key, name, fdict, cdict))
  687.             result = result + self.bigsection(
  688.                 'Classes', '#ffffff', '#ee77aa', join(contents))
  689.         if funcs:
  690.             contents = []
  691.             for key, value in funcs:
  692.                 contents.append(self.document(value, key, name, fdict, cdict))
  693.             result = result + self.bigsection(
  694.                 'Functions', '#ffffff', '#eeaa77', join(contents))
  695.         if data:
  696.             contents = []
  697.             for key, value in data:
  698.                 contents.append(self.document(value, key))
  699.             result = result + self.bigsection(
  700.                 'Data', '#ffffff', '#55aa55', join(contents, '<br>\n'))
  701.         if hasattr(object, '__author__'):
  702.             contents = self.markup(str(object.__author__), self.preformat)
  703.             result = result + self.bigsection(
  704.                 'Author', '#ffffff', '#7799ee', contents)
  705.         if hasattr(object, '__credits__'):
  706.             contents = self.markup(str(object.__credits__), self.preformat)
  707.             result = result + self.bigsection(
  708.                 'Credits', '#ffffff', '#7799ee', contents)
  709.  
  710.         return result
  711.  
  712.     def docclass(self, object, name=None, mod=None, funcs={}, classes={},
  713.                  *ignored):
  714.         """Produce HTML documentation for a class object."""
  715.         realname = object.__name__
  716.         name = name or realname
  717.         bases = object.__bases__
  718.  
  719.         contents = []
  720.         push = contents.append
  721.  
  722.         # Cute little class to pump out a horizontal rule between sections.
  723.         class HorizontalRule:
  724.             def __init__(self):
  725.                 self.needone = 0
  726.             def maybe(self):
  727.                 if self.needone:
  728.                     push('<hr>\n')
  729.                 self.needone = 1
  730.         hr = HorizontalRule()
  731.  
  732.         # List the mro, if non-trivial.
  733.         mro = deque(inspect.getmro(object))
  734.         if len(mro) > 2:
  735.             hr.maybe()
  736.             push('<dl><dt>Method resolution order:</dt>\n')
  737.             for base in mro:
  738.                 push('<dd>%s</dd>\n' % self.classlink(base,
  739.                                                       object.__module__))
  740.             push('</dl>\n')
  741.  
  742.         def spill(msg, attrs, predicate):
  743.             ok, attrs = _split_list(attrs, predicate)
  744.             if ok:
  745.                 hr.maybe()
  746.                 push(msg)
  747.                 for name, kind, homecls, value in ok:
  748.                     push(self.document(getattr(object, name), name, mod,
  749.                                        funcs, classes, mdict, object))
  750.                     push('\n')
  751.             return attrs
  752.  
  753.         def spilldescriptors(msg, attrs, predicate):
  754.             ok, attrs = _split_list(attrs, predicate)
  755.             if ok:
  756.                 hr.maybe()
  757.                 push(msg)
  758.                 for name, kind, homecls, value in ok:
  759.                     push(self._docdescriptor(name, value, mod))
  760.             return attrs
  761.  
  762.         def spilldata(msg, attrs, predicate):
  763.             ok, attrs = _split_list(attrs, predicate)
  764.             if ok:
  765.                 hr.maybe()
  766.                 push(msg)
  767.                 for name, kind, homecls, value in ok:
  768.                     base = self.docother(getattr(object, name), name, mod)
  769.                     if (hasattr(value, '__call__') or
  770.                             inspect.isdatadescriptor(value)):
  771.                         doc = getattr(value, "__doc__", None)
  772.                     else:
  773.                         doc = None
  774.                     if doc is None:
  775.                         push('<dl><dt>%s</dl>\n' % base)
  776.                     else:
  777.                         doc = self.markup(getdoc(value), self.preformat,
  778.                                           funcs, classes, mdict)
  779.                         doc = '<dd><tt>%s</tt>' % doc
  780.                         push('<dl><dt>%s%s</dl>\n' % (base, doc))
  781.                     push('\n')
  782.             return attrs
  783.  
  784.         attrs = filter(lambda data: visiblename(data[0]),
  785.                        classify_class_attrs(object))
  786.         mdict = {}
  787.         for key, kind, homecls, value in attrs:
  788.             mdict[key] = anchor = '#' + name + '-' + key
  789.             value = getattr(object, key)
  790.             try:
  791.                 # The value may not be hashable (e.g., a data attr with
  792.                 # a dict or list value).
  793.                 mdict[value] = anchor
  794.             except TypeError:
  795.                 pass
  796.  
  797.         while attrs:
  798.             if mro:
  799.                 thisclass = mro.popleft()
  800.             else:
  801.                 thisclass = attrs[0][2]
  802.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  803.  
  804.             if thisclass is __builtin__.object:
  805.                 attrs = inherited
  806.                 continue
  807.             elif thisclass is object:
  808.                 tag = 'defined here'
  809.             else:
  810.                 tag = 'inherited from %s' % self.classlink(thisclass,
  811.                                                            object.__module__)
  812.             tag += ':<br>\n'
  813.  
  814.             # Sort attrs by name.
  815.             try:
  816.                 attrs.sort(key=lambda t: t[0])
  817.             except TypeError:
  818.                 attrs.sort(lambda t1, t2: cmp(t1[0], t2[0]))    # 2.3 compat
  819.  
  820.             # Pump out the attrs, segregated by kind.
  821.             attrs = spill('Methods %s' % tag, attrs,
  822.                           lambda t: t[1] == 'method')
  823.             attrs = spill('Class methods %s' % tag, attrs,
  824.                           lambda t: t[1] == 'class method')
  825.             attrs = spill('Static methods %s' % tag, attrs,
  826.                           lambda t: t[1] == 'static method')
  827.             attrs = spilldescriptors('Data descriptors %s' % tag, attrs,
  828.                                      lambda t: t[1] == 'data descriptor')
  829.             attrs = spilldata('Data and other attributes %s' % tag, attrs,
  830.                               lambda t: t[1] == 'data')
  831.             assert attrs == []
  832.             attrs = inherited
  833.  
  834.         contents = ''.join(contents)
  835.  
  836.         if name == realname:
  837.             title = '<a name="%s">class <strong>%s</strong></a>' % (
  838.                 name, realname)
  839.         else:
  840.             title = '<strong>%s</strong> = <a name="%s">class %s</a>' % (
  841.                 name, name, realname)
  842.         if bases:
  843.             parents = []
  844.             for base in bases:
  845.                 parents.append(self.classlink(base, object.__module__))
  846.             title = title + '(%s)' % join(parents, ', ')
  847.         doc = self.markup(getdoc(object), self.preformat, funcs, classes, mdict)
  848.         doc = doc and '<tt>%s<br> </tt>' % doc
  849.  
  850.         return self.section(title, '#000000', '#ffc8d8', contents, 3, doc)
  851.  
  852.     def formatvalue(self, object):
  853.         """Format an argument default value as text."""
  854.         return self.grey('=' + self.repr(object))
  855.  
  856.     def docroutine(self, object, name=None, mod=None,
  857.                    funcs={}, classes={}, methods={}, cl=None):
  858.         """Produce HTML documentation for a function or method object."""
  859.         realname = object.__name__
  860.         name = name or realname
  861.         anchor = (cl and cl.__name__ or '') + '-' + name
  862.         note = ''
  863.         skipdocs = 0
  864.         if inspect.ismethod(object):
  865.             imclass = object.im_class
  866.             if cl:
  867.                 if imclass is not cl:
  868.                     note = ' from ' + self.classlink(imclass, mod)
  869.             else:
  870.                 if object.im_self is not None:
  871.                     note = ' method of %s instance' % self.classlink(
  872.                         object.im_self.__class__, mod)
  873.                 else:
  874.                     note = ' unbound %s method' % self.classlink(imclass,mod)
  875.             object = object.im_func
  876.  
  877.         if name == realname:
  878.             title = '<a name="%s"><strong>%s</strong></a>' % (anchor, realname)
  879.         else:
  880.             if (cl and realname in cl.__dict__ and
  881.                 cl.__dict__[realname] is object):
  882.                 reallink = '<a href="#%s">%s</a>' % (
  883.                     cl.__name__ + '-' + realname, realname)
  884.                 skipdocs = 1
  885.             else:
  886.                 reallink = realname
  887.             title = '<a name="%s"><strong>%s</strong></a> = %s' % (
  888.                 anchor, name, reallink)
  889.         if inspect.isfunction(object):
  890.             args, varargs, varkw, defaults = inspect.getargspec(object)
  891.             argspec = inspect.formatargspec(
  892.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  893.             if realname == '<lambda>':
  894.                 title = '<strong>%s</strong> <em>lambda</em> ' % name
  895.                 argspec = argspec[1:-1] # remove parentheses
  896.         else:
  897.             argspec = '(...)'
  898.  
  899.         decl = title + argspec + (note and self.grey(
  900.                '<font face="helvetica, arial">%s</font>' % note))
  901.  
  902.         if skipdocs:
  903.             return '<dl><dt>%s</dt></dl>\n' % decl
  904.         else:
  905.             doc = self.markup(
  906.                 getdoc(object), self.preformat, funcs, classes, methods)
  907.             doc = doc and '<dd><tt>%s</tt></dd>' % doc
  908.             return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
  909.  
  910.     def _docdescriptor(self, name, value, mod):
  911.         results = []
  912.         push = results.append
  913.  
  914.         if name:
  915.             push('<dl><dt><strong>%s</strong></dt>\n' % name)
  916.         if value.__doc__ is not None:
  917.             doc = self.markup(getdoc(value), self.preformat)
  918.             push('<dd><tt>%s</tt></dd>\n' % doc)
  919.         push('</dl>\n')
  920.  
  921.         return ''.join(results)
  922.  
  923.     def docproperty(self, object, name=None, mod=None, cl=None):
  924.         """Produce html documentation for a property."""
  925.         return self._docdescriptor(name, object, mod)
  926.  
  927.     def docother(self, object, name=None, mod=None, *ignored):
  928.         """Produce HTML documentation for a data object."""
  929.         lhs = name and '<strong>%s</strong> = ' % name or ''
  930.         return lhs + self.repr(object)
  931.  
  932.     def docdata(self, object, name=None, mod=None, cl=None):
  933.         """Produce html documentation for a data descriptor."""
  934.         return self._docdescriptor(name, object, mod)
  935.  
  936.     def index(self, dir, shadowed=None):
  937.         """Generate an HTML index for a directory of modules."""
  938.         modpkgs = []
  939.         if shadowed is None: shadowed = {}
  940.         for importer, name, ispkg in pkgutil.iter_modules([dir]):
  941.             modpkgs.append((name, '', ispkg, name in shadowed))
  942.             shadowed[name] = 1
  943.  
  944.         modpkgs.sort()
  945.         contents = self.multicolumn(modpkgs, self.modpkglink)
  946.         return self.bigsection(dir, '#ffffff', '#ee77aa', contents)
  947.  
  948. # -------------------------------------------- text documentation generator
  949.  
  950. class TextRepr(Repr):
  951.     """Class for safely making a text representation of a Python object."""
  952.     def __init__(self):
  953.         Repr.__init__(self)
  954.         self.maxlist = self.maxtuple = 20
  955.         self.maxdict = 10
  956.         self.maxstring = self.maxother = 100
  957.  
  958.     def repr1(self, x, level):
  959.         if hasattr(type(x), '__name__'):
  960.             methodname = 'repr_' + join(split(type(x).__name__), '_')
  961.             if hasattr(self, methodname):
  962.                 return getattr(self, methodname)(x, level)
  963.         return cram(stripid(repr(x)), self.maxother)
  964.  
  965.     def repr_string(self, x, level):
  966.         test = cram(x, self.maxstring)
  967.         testrepr = repr(test)
  968.         if '\\' in test and '\\' not in replace(testrepr, r'\\', ''):
  969.             # Backslashes are only literal in the string and are never
  970.             # needed to make any special characters, so show a raw string.
  971.             return 'r' + testrepr[0] + test + testrepr[0]
  972.         return testrepr
  973.  
  974.     repr_str = repr_string
  975.  
  976.     def repr_instance(self, x, level):
  977.         try:
  978.             return cram(stripid(repr(x)), self.maxstring)
  979.         except:
  980.             return '<%s instance>' % x.__class__.__name__
  981.  
  982. class TextDoc(Doc):
  983.     """Formatter class for text documentation."""
  984.  
  985.     # ------------------------------------------- text formatting utilities
  986.  
  987.     _repr_instance = TextRepr()
  988.     repr = _repr_instance.repr
  989.  
  990.     def bold(self, text):
  991.         """Format a string in bold by overstriking."""
  992.         return join(map(lambda ch: ch + '\b' + ch, text), '')
  993.  
  994.     def indent(self, text, prefix='    '):
  995.         """Indent text by prepending a given prefix to each line."""
  996.         if not text: return ''
  997.         lines = split(text, '\n')
  998.         lines = map(lambda line, prefix=prefix: prefix + line, lines)
  999.         if lines: lines[-1] = rstrip(lines[-1])
  1000.         return join(lines, '\n')
  1001.  
  1002.     def section(self, title, contents):
  1003.         """Format a section with a given heading."""
  1004.         return self.bold(title) + '\n' + rstrip(self.indent(contents)) + '\n\n'
  1005.  
  1006.     # ---------------------------------------------- type-specific routines
  1007.  
  1008.     def formattree(self, tree, modname, parent=None, prefix=''):
  1009.         """Render in text a class tree as returned by inspect.getclasstree()."""
  1010.         result = ''
  1011.         for entry in tree:
  1012.             if type(entry) is type(()):
  1013.                 c, bases = entry
  1014.                 result = result + prefix + classname(c, modname)
  1015.                 if bases and bases != (parent,):
  1016.                     parents = map(lambda c, m=modname: classname(c, m), bases)
  1017.                     result = result + '(%s)' % join(parents, ', ')
  1018.                 result = result + '\n'
  1019.             elif type(entry) is type([]):
  1020.                 result = result + self.formattree(
  1021.                     entry, modname, c, prefix + '    ')
  1022.         return result
  1023.  
  1024.     def docmodule(self, object, name=None, mod=None):
  1025.         """Produce text documentation for a given module object."""
  1026.         name = object.__name__ # ignore the passed-in name
  1027.         synop, desc = splitdoc(getdoc(object))
  1028.         result = self.section('NAME', name + (synop and ' - ' + synop))
  1029.  
  1030.         try:
  1031.             all = object.__all__
  1032.         except AttributeError:
  1033.             all = None
  1034.  
  1035.         try:
  1036.             file = inspect.getabsfile(object)
  1037.         except TypeError:
  1038.             file = '(built-in)'
  1039.         result = result + self.section('FILE', file)
  1040.  
  1041.         docloc = self.getdocloc(object)
  1042.         if docloc is not None:
  1043.             result = result + self.section('MODULE DOCS', docloc)
  1044.  
  1045.         if desc:
  1046.             result = result + self.section('DESCRIPTION', desc)
  1047.  
  1048.         classes = []
  1049.         for key, value in inspect.getmembers(object, inspect.isclass):
  1050.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  1051.             if (all is not None
  1052.                 or (inspect.getmodule(value) or object) is object):
  1053.                 if visiblename(key, all):
  1054.                     classes.append((key, value))
  1055.         funcs = []
  1056.         for key, value in inspect.getmembers(object, inspect.isroutine):
  1057.             # if __all__ exists, believe it.  Otherwise use old heuristic.
  1058.             if (all is not None or
  1059.                 inspect.isbuiltin(value) or inspect.getmodule(value) is object):
  1060.                 if visiblename(key, all):
  1061.                     funcs.append((key, value))
  1062.         data = []
  1063.         for key, value in inspect.getmembers(object, isdata):
  1064.             if visiblename(key, all):
  1065.                 data.append((key, value))
  1066.  
  1067.         modpkgs = []
  1068.         modpkgs_names = set()
  1069.         if hasattr(object, '__path__'):
  1070.             for importer, modname, ispkg in pkgutil.iter_modules(object.__path__):
  1071.                 modpkgs_names.add(modname)
  1072.                 if ispkg:
  1073.                     modpkgs.append(modname + ' (package)')
  1074.                 else:
  1075.                     modpkgs.append(modname)
  1076.  
  1077.             modpkgs.sort()
  1078.             result = result + self.section(
  1079.                 'PACKAGE CONTENTS', join(modpkgs, '\n'))
  1080.  
  1081.         # Detect submodules as sometimes created by C extensions
  1082.         submodules = []
  1083.         for key, value in inspect.getmembers(object, inspect.ismodule):
  1084.             if value.__name__.startswith(name + '.') and key not in modpkgs_names:
  1085.                 submodules.append(key)
  1086.         if submodules:
  1087.             submodules.sort()
  1088.             result = result + self.section(
  1089.                 'SUBMODULES', join(submodules, '\n'))
  1090.  
  1091.         if classes:
  1092.             classlist = map(lambda key_value: key_value[1], classes)
  1093.             contents = [self.formattree(
  1094.                 inspect.getclasstree(classlist, 1), name)]
  1095.             for key, value in classes:
  1096.                 contents.append(self.document(value, key, name))
  1097.             result = result + self.section('CLASSES', join(contents, '\n'))
  1098.  
  1099.         if funcs:
  1100.             contents = []
  1101.             for key, value in funcs:
  1102.                 contents.append(self.document(value, key, name))
  1103.             result = result + self.section('FUNCTIONS', join(contents, '\n'))
  1104.  
  1105.         if data:
  1106.             contents = []
  1107.             for key, value in data:
  1108.                 contents.append(self.docother(value, key, name, maxlen=70))
  1109.             result = result + self.section('DATA', join(contents, '\n'))
  1110.  
  1111.         if hasattr(object, '__version__'):
  1112.             version = str(object.__version__)
  1113.             if version[:11] == '$' + 'Revision: ' and version[-1:] == '$':
  1114.                 version = strip(version[11:-1])
  1115.             result = result + self.section('VERSION', version)
  1116.         if hasattr(object, '__date__'):
  1117.             result = result + self.section('DATE', str(object.__date__))
  1118.         if hasattr(object, '__author__'):
  1119.             result = result + self.section('AUTHOR', str(object.__author__))
  1120.         if hasattr(object, '__credits__'):
  1121.             result = result + self.section('CREDITS', str(object.__credits__))
  1122.         return result
  1123.  
  1124.     def docclass(self, object, name=None, mod=None):
  1125.         """Produce text documentation for a given class object."""
  1126.         realname = object.__name__
  1127.         name = name or realname
  1128.         bases = object.__bases__
  1129.  
  1130.         def makename(c, m=object.__module__):
  1131.             return classname(c, m)
  1132.  
  1133.         if name == realname:
  1134.             title = 'class ' + self.bold(realname)
  1135.         else:
  1136.             title = self.bold(name) + ' = class ' + realname
  1137.         if bases:
  1138.             parents = map(makename, bases)
  1139.             title = title + '(%s)' % join(parents, ', ')
  1140.  
  1141.         doc = getdoc(object)
  1142.         contents = doc and [doc + '\n'] or []
  1143.         push = contents.append
  1144.  
  1145.         # List the mro, if non-trivial.
  1146.         mro = deque(inspect.getmro(object))
  1147.         if len(mro) > 2:
  1148.             push("Method resolution order:")
  1149.             for base in mro:
  1150.                 push('    ' + makename(base))
  1151.             push('')
  1152.  
  1153.         # Cute little class to pump out a horizontal rule between sections.
  1154.         class HorizontalRule:
  1155.             def __init__(self):
  1156.                 self.needone = 0
  1157.             def maybe(self):
  1158.                 if self.needone:
  1159.                     push('-' * 70)
  1160.                 self.needone = 1
  1161.         hr = HorizontalRule()
  1162.  
  1163.         def spill(msg, attrs, predicate):
  1164.             ok, attrs = _split_list(attrs, predicate)
  1165.             if ok:
  1166.                 hr.maybe()
  1167.                 push(msg)
  1168.                 for name, kind, homecls, value in ok:
  1169.                     push(self.document(getattr(object, name),
  1170.                                        name, mod, object))
  1171.             return attrs
  1172.  
  1173.         def spilldescriptors(msg, attrs, predicate):
  1174.             ok, attrs = _split_list(attrs, predicate)
  1175.             if ok:
  1176.                 hr.maybe()
  1177.                 push(msg)
  1178.                 for name, kind, homecls, value in ok:
  1179.                     push(self._docdescriptor(name, value, mod))
  1180.             return attrs
  1181.  
  1182.         def spilldata(msg, attrs, predicate):
  1183.             ok, attrs = _split_list(attrs, predicate)
  1184.             if ok:
  1185.                 hr.maybe()
  1186.                 push(msg)
  1187.                 for name, kind, homecls, value in ok:
  1188.                     if (hasattr(value, '__call__') or
  1189.                             inspect.isdatadescriptor(value)):
  1190.                         doc = getdoc(value)
  1191.                     else:
  1192.                         doc = None
  1193.                     push(self.docother(getattr(object, name),
  1194.                                        name, mod, maxlen=70, doc=doc) + '\n')
  1195.             return attrs
  1196.  
  1197.         attrs = filter(lambda data: visiblename(data[0]),
  1198.                        classify_class_attrs(object))
  1199.         while attrs:
  1200.             if mro:
  1201.                 thisclass = mro.popleft()
  1202.             else:
  1203.                 thisclass = attrs[0][2]
  1204.             attrs, inherited = _split_list(attrs, lambda t: t[2] is thisclass)
  1205.  
  1206.             if thisclass is __builtin__.object:
  1207.                 attrs = inherited
  1208.                 continue
  1209.             elif thisclass is object:
  1210.                 tag = "defined here"
  1211.             else:
  1212.                 tag = "inherited from %s" % classname(thisclass,
  1213.                                                       object.__module__)
  1214.  
  1215.             # Sort attrs by name.
  1216.             attrs.sort()
  1217.  
  1218.             # Pump out the attrs, segregated by kind.
  1219.             attrs = spill("Methods %s:\n" % tag, attrs,
  1220.                           lambda t: t[1] == 'method')
  1221.             attrs = spill("Class methods %s:\n" % tag, attrs,
  1222.                           lambda t: t[1] == 'class method')
  1223.             attrs = spill("Static methods %s:\n" % tag, attrs,
  1224.                           lambda t: t[1] == 'static method')
  1225.             attrs = spilldescriptors("Data descriptors %s:\n" % tag, attrs,
  1226.                                      lambda t: t[1] == 'data descriptor')
  1227.             attrs = spilldata("Data and other attributes %s:\n" % tag, attrs,
  1228.                               lambda t: t[1] == 'data')
  1229.             assert attrs == []
  1230.             attrs = inherited
  1231.  
  1232.         contents = '\n'.join(contents)
  1233.         if not contents:
  1234.             return title + '\n'
  1235.         return title + '\n' + self.indent(rstrip(contents), ' |  ') + '\n'
  1236.  
  1237.     def formatvalue(self, object):
  1238.         """Format an argument default value as text."""
  1239.         return '=' + self.repr(object)
  1240.  
  1241.     def docroutine(self, object, name=None, mod=None, cl=None):
  1242.         """Produce text documentation for a function or method object."""
  1243.         realname = object.__name__
  1244.         name = name or realname
  1245.         note = ''
  1246.         skipdocs = 0
  1247.         if inspect.ismethod(object):
  1248.             imclass = object.im_class
  1249.             if cl:
  1250.                 if imclass is not cl:
  1251.                     note = ' from ' + classname(imclass, mod)
  1252.             else:
  1253.                 if object.im_self is not None:
  1254.                     note = ' method of %s instance' % classname(
  1255.                         object.im_self.__class__, mod)
  1256.                 else:
  1257.                     note = ' unbound %s method' % classname(imclass,mod)
  1258.             object = object.im_func
  1259.  
  1260.         if name == realname:
  1261.             title = self.bold(realname)
  1262.         else:
  1263.             if (cl and realname in cl.__dict__ and
  1264.                 cl.__dict__[realname] is object):
  1265.                 skipdocs = 1
  1266.             title = self.bold(name) + ' = ' + realname
  1267.         if inspect.isfunction(object):
  1268.             args, varargs, varkw, defaults = inspect.getargspec(object)
  1269.             argspec = inspect.formatargspec(
  1270.                 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
  1271.             if realname == '<lambda>':
  1272.                 title = self.bold(name) + ' lambda '
  1273.                 argspec = argspec[1:-1] # remove parentheses
  1274.         else:
  1275.             argspec = '(...)'
  1276.         decl = title + argspec + note
  1277.  
  1278.         if skipdocs:
  1279.             return decl + '\n'
  1280.         else:
  1281.             doc = getdoc(object) or ''
  1282.             return decl + '\n' + (doc and rstrip(self.indent(doc)) + '\n')
  1283.  
  1284.     def _docdescriptor(self, name, value, mod):
  1285.         results = []
  1286.         push = results.append
  1287.  
  1288.         if name:
  1289.             push(self.bold(name))
  1290.             push('\n')
  1291.         doc = getdoc(value) or ''
  1292.         if doc:
  1293.             push(self.indent(doc))
  1294.             push('\n')
  1295.         return ''.join(results)
  1296.  
  1297.     def docproperty(self, object, name=None, mod=None, cl=None):
  1298.         """Produce text documentation for a property."""
  1299.         return self._docdescriptor(name, object, mod)
  1300.  
  1301.     def docdata(self, object, name=None, mod=None, cl=None):
  1302.         """Produce text documentation for a data descriptor."""
  1303.         return self._docdescriptor(name, object, mod)
  1304.  
  1305.     def docother(self, object, name=None, mod=None, parent=None, maxlen=None, doc=None):
  1306.         """Produce text documentation for a data object."""
  1307.         repr = self.repr(object)
  1308.         if maxlen:
  1309.             line = (name and name + ' = ' or '') + repr
  1310.             chop = maxlen - len(line)
  1311.             if chop < 0: repr = repr[:chop] + '...'
  1312.         line = (name and self.bold(name) + ' = ' or '') + repr
  1313.         if doc is not None:
  1314.             line += '\n' + self.indent(str(doc))
  1315.         return line
  1316.  
  1317. # --------------------------------------------------------- user interfaces
  1318.  
  1319. def pager(text):
  1320.     """The first time this is called, determine what kind of pager to use."""
  1321.     global pager
  1322.     pager = getpager()
  1323.     pager(text)
  1324.  
  1325. def getpager():
  1326.     """Decide what method to use for paging through text."""
  1327.     if type(sys.stdout) is not types.FileType:
  1328.         return plainpager
  1329.     if not sys.stdin.isatty() or not sys.stdout.isatty():
  1330.         return plainpager
  1331.     if 'PAGER' in os.environ:
  1332.         if sys.platform == 'win32': # pipes completely broken in Windows
  1333.             return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
  1334.         elif os.environ.get('TERM') in ('dumb', 'emacs'):
  1335.             return lambda text: pipepager(plain(text), os.environ['PAGER'])
  1336.         else:
  1337.             return lambda text: pipepager(text, os.environ['PAGER'])
  1338.     if os.environ.get('TERM') in ('dumb', 'emacs'):
  1339.         return plainpager
  1340.     if sys.platform == 'win32' or sys.platform.startswith('os2'):
  1341.         return lambda text: tempfilepager(plain(text), 'more <')
  1342.     if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
  1343.         return lambda text: pipepager(text, 'less')
  1344.  
  1345.     import tempfile
  1346.     (fd, filename) = tempfile.mkstemp()
  1347.     os.close(fd)
  1348.     try:
  1349.         if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
  1350.             return lambda text: pipepager(text, 'more')
  1351.         else:
  1352.             return ttypager
  1353.     finally:
  1354.         os.unlink(filename)
  1355.  
  1356. def plain(text):
  1357.     """Remove boldface formatting from text."""
  1358.     return re.sub('.\b', '', text)
  1359.  
  1360. def pipepager(text, cmd):
  1361.     """Page through text by feeding it to another program."""
  1362.     pipe = os.popen(cmd, 'w')
  1363.     try:
  1364.         pipe.write(text)
  1365.         pipe.close()
  1366.     except IOError:
  1367.         pass # Ignore broken pipes caused by quitting the pager program.
  1368.  
  1369. def tempfilepager(text, cmd):
  1370.     """Page through text by invoking a program on a temporary file."""
  1371.     import tempfile
  1372.     filename = tempfile.mktemp()
  1373.     file = open(filename, 'w')
  1374.     file.write(text)
  1375.     file.close()
  1376.     try:
  1377.         os.system(cmd + ' "' + filename + '"')
  1378.     finally:
  1379.         os.unlink(filename)
  1380.  
  1381. def ttypager(text):
  1382.     """Page through text on a text terminal."""
  1383.     lines = split(plain(text), '\n')
  1384.     try:
  1385.         import tty
  1386.         fd = sys.stdin.fileno()
  1387.         old = tty.tcgetattr(fd)
  1388.         tty.setcbreak(fd)
  1389.         getchar = lambda: sys.stdin.read(1)
  1390.     except (ImportError, AttributeError):
  1391.         tty = None
  1392.         getchar = lambda: sys.stdin.readline()[:-1][:1]
  1393.  
  1394.     try:
  1395.         r = inc = os.environ.get('LINES', 25) - 1
  1396.         sys.stdout.write(join(lines[:inc], '\n') + '\n')
  1397.         while lines[r:]:
  1398.             sys.stdout.write('-- more --')
  1399.             sys.stdout.flush()
  1400.             c = getchar()
  1401.  
  1402.             if c in ('q', 'Q'):
  1403.                 sys.stdout.write('\r          \r')
  1404.                 break
  1405.             elif c in ('\r', '\n'):
  1406.                 sys.stdout.write('\r          \r' + lines[r] + '\n')
  1407.                 r = r + 1
  1408.                 continue
  1409.             if c in ('b', 'B', '\x1b'):
  1410.                 r = r - inc - inc
  1411.                 if r < 0: r = 0
  1412.             sys.stdout.write('\n' + join(lines[r:r+inc], '\n') + '\n')
  1413.             r = r + inc
  1414.  
  1415.     finally:
  1416.         if tty:
  1417.             tty.tcsetattr(fd, tty.TCSAFLUSH, old)
  1418.  
  1419. def plainpager(text):
  1420.     """Simply print unformatted text.  This is the ultimate fallback."""
  1421.     sys.stdout.write(plain(text))
  1422.  
  1423. def describe(thing):
  1424.     """Produce a short description of the given thing."""
  1425.     if inspect.ismodule(thing):
  1426.         if thing.__name__ in sys.builtin_module_names:
  1427.             return 'built-in module ' + thing.__name__
  1428.         if hasattr(thing, '__path__'):
  1429.             return 'package ' + thing.__name__
  1430.         else:
  1431.             return 'module ' + thing.__name__
  1432.     if inspect.isbuiltin(thing):
  1433.         return 'built-in function ' + thing.__name__
  1434.     if inspect.isgetsetdescriptor(thing):
  1435.         return 'getset descriptor %s.%s.%s' % (
  1436.             thing.__objclass__.__module__, thing.__objclass__.__name__,
  1437.             thing.__name__)
  1438.     if inspect.ismemberdescriptor(thing):
  1439.         return 'member descriptor %s.%s.%s' % (
  1440.             thing.__objclass__.__module__, thing.__objclass__.__name__,
  1441.             thing.__name__)
  1442.     if inspect.isclass(thing):
  1443.         return 'class ' + thing.__name__
  1444.     if inspect.isfunction(thing):
  1445.         return 'function ' + thing.__name__
  1446.     if inspect.ismethod(thing):
  1447.         return 'method ' + thing.__name__
  1448.     if type(thing) is types.InstanceType:
  1449.         return 'instance of ' + thing.__class__.__name__
  1450.     return type(thing).__name__
  1451.  
  1452. def locate(path, forceload=0):
  1453.     """Locate an object by name or dotted path, importing as necessary."""
  1454.     parts = [part for part in split(path, '.') if part]
  1455.     module, n = None, 0
  1456.     while n < len(parts):
  1457.         nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
  1458.         if nextmodule: module, n = nextmodule, n + 1
  1459.         else: break
  1460.     if module:
  1461.         object = module
  1462.         for part in parts[n:]:
  1463.             try: object = getattr(object, part)
  1464.             except AttributeError: return None
  1465.         return object
  1466.     else:
  1467.         if hasattr(__builtin__, path):
  1468.             return getattr(__builtin__, path)
  1469.  
  1470. # --------------------------------------- interactive interpreter interface
  1471.  
  1472. text = TextDoc()
  1473. html = HTMLDoc()
  1474.  
  1475. class _OldStyleClass: pass
  1476. _OLD_INSTANCE_TYPE = type(_OldStyleClass())
  1477.  
  1478. def resolve(thing, forceload=0):
  1479.     """Given an object or a path to an object, get the object and its name."""
  1480.     if isinstance(thing, str):
  1481.         object = locate(thing, forceload)
  1482.         if not object:
  1483.             raise ImportError, 'no Python documentation found for %r' % thing
  1484.         return object, thing
  1485.     else:
  1486.         return thing, getattr(thing, '__name__', None)
  1487.  
  1488. def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
  1489.     """Render text documentation, given an object or a path to an object."""
  1490.     object, name = resolve(thing, forceload)
  1491.     desc = describe(object)
  1492.     module = inspect.getmodule(object)
  1493.     if name and '.' in name:
  1494.         desc += ' in ' + name[:name.rfind('.')]
  1495.     elif module and module is not object:
  1496.         desc += ' in module ' + module.__name__
  1497.     if type(object) is _OLD_INSTANCE_TYPE:
  1498.         # If the passed object is an instance of an old-style class,
  1499.         # document its available methods instead of its value.
  1500.         object = object.__class__
  1501.     elif not (inspect.ismodule(object) or
  1502.               inspect.isclass(object) or
  1503.               inspect.isroutine(object) or
  1504.               inspect.isgetsetdescriptor(object) or
  1505.               inspect.ismemberdescriptor(object) or
  1506.               isinstance(object, property)):
  1507.         # If the passed object is a piece of data or an instance,
  1508.         # document its available methods instead of its value.
  1509.         object = type(object)
  1510.         desc += ' object'
  1511.     return title % desc + '\n\n' + text.document(object, name)
  1512.  
  1513. def doc(thing, title='Python Library Documentation: %s', forceload=0):
  1514.     """Display text documentation, given an object or a path to an object."""
  1515.     try:
  1516.         pager(render_doc(thing, title, forceload))
  1517.     except (ImportError, ErrorDuringImport), value:
  1518.         print value
  1519.  
  1520. def writedoc(thing, forceload=0):
  1521.     """Write HTML documentation to a file in the current directory."""
  1522.     try:
  1523.         object, name = resolve(thing, forceload)
  1524.         page = html.page(describe(object), html.document(object, name))
  1525.         file = open(name + '.html', 'w')
  1526.         file.write(page)
  1527.         file.close()
  1528.         print 'wrote', name + '.html'
  1529.     except (ImportError, ErrorDuringImport), value:
  1530.         print value
  1531.  
  1532. def writedocs(dir, pkgpath='', done=None):
  1533.     """Write out HTML documentation for all modules in a directory tree."""
  1534.     if done is None: done = {}
  1535.     for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):
  1536.         writedoc(modname)
  1537.     return
  1538.  
  1539. class Helper:
  1540.  
  1541.     # These dictionaries map a topic name to either an alias, or a tuple
  1542.     # (label, seealso-items).  The "label" is the label of the corresponding
  1543.     # section in the .rst file under Doc/ and an index into the dictionary
  1544.     # in pydoc_topics.py.
  1545.     #
  1546.     # CAUTION: if you change one of these dictionaries, be sure to adapt the
  1547.     #          list of needed labels in Doc/tools/sphinxext/pyspecific.py and
  1548.     #          regenerate the pydoc_topics.py file by running
  1549.     #              make pydoc-topics
  1550.     #          in Doc/ and copying the output file into the Lib/ directory.
  1551.  
  1552.     keywords = {
  1553.         'and': 'BOOLEAN',
  1554.         'as': 'with',
  1555.         'assert': ('assert', ''),
  1556.         'break': ('break', 'while for'),
  1557.         'class': ('class', 'CLASSES SPECIALMETHODS'),
  1558.         'continue': ('continue', 'while for'),
  1559.         'def': ('function', ''),
  1560.         'del': ('del', 'BASICMETHODS'),
  1561.         'elif': 'if',
  1562.         'else': ('else', 'while for'),
  1563.         'except': 'try',
  1564.         'exec': ('exec', ''),
  1565.         'finally': 'try',
  1566.         'for': ('for', 'break continue while'),
  1567.         'from': 'import',
  1568.         'global': ('global', 'NAMESPACES'),
  1569.         'if': ('if', 'TRUTHVALUE'),
  1570.         'import': ('import', 'MODULES'),
  1571.         'in': ('in', 'SEQUENCEMETHODS2'),
  1572.         'is': 'COMPARISON',
  1573.         'lambda': ('lambda', 'FUNCTIONS'),
  1574.         'not': 'BOOLEAN',
  1575.         'or': 'BOOLEAN',
  1576.         'pass': ('pass', ''),
  1577.         'print': ('print', ''),
  1578.         'raise': ('raise', 'EXCEPTIONS'),
  1579.         'return': ('return', 'FUNCTIONS'),
  1580.         'try': ('try', 'EXCEPTIONS'),
  1581.         'while': ('while', 'break continue if TRUTHVALUE'),
  1582.         'with': ('with', 'CONTEXTMANAGERS EXCEPTIONS yield'),
  1583.         'yield': ('yield', ''),
  1584.     }
  1585.     # Either add symbols to this dictionary or to the symbols dictionary
  1586.     # directly: Whichever is easier. They are merged later.
  1587.     _symbols_inverse = {
  1588.         'STRINGS' : ("'", "'''", "r'", "u'", '"""', '"', 'r"', 'u"'),
  1589.         'OPERATORS' : ('+', '-', '*', '**', '/', '//', '%', '<<', '>>', '&',
  1590.                        '|', '^', '~', '<', '>', '<=', '>=', '==', '!=', '<>'),
  1591.         'COMPARISON' : ('<', '>', '<=', '>=', '==', '!=', '<>'),
  1592.         'UNARY' : ('-', '~'),
  1593.         'AUGMENTEDASSIGNMENT' : ('+=', '-=', '*=', '/=', '%=', '&=', '|=',
  1594.                                 '^=', '<<=', '>>=', '**=', '//='),
  1595.         'BITWISE' : ('<<', '>>', '&', '|', '^', '~'),
  1596.         'COMPLEX' : ('j', 'J')
  1597.     }
  1598.     symbols = {
  1599.         '%': 'OPERATORS FORMATTING',
  1600.         '**': 'POWER',
  1601.         ',': 'TUPLES LISTS FUNCTIONS',
  1602.         '.': 'ATTRIBUTES FLOAT MODULES OBJECTS',
  1603.         '...': 'ELLIPSIS',
  1604.         ':': 'SLICINGS DICTIONARYLITERALS',
  1605.         '@': 'def class',
  1606.         '\\': 'STRINGS',
  1607.         '_': 'PRIVATENAMES',
  1608.         '__': 'PRIVATENAMES SPECIALMETHODS',
  1609.         '`': 'BACKQUOTES',
  1610.         '(': 'TUPLES FUNCTIONS CALLS',
  1611.         ')': 'TUPLES FUNCTIONS CALLS',
  1612.         '[': 'LISTS SUBSCRIPTS SLICINGS',
  1613.         ']': 'LISTS SUBSCRIPTS SLICINGS'
  1614.     }
  1615.     for topic, symbols_ in _symbols_inverse.iteritems():
  1616.         for symbol in symbols_:
  1617.             topics = symbols.get(symbol, topic)
  1618.             if topic not in topics:
  1619.                 topics = topics + ' ' + topic
  1620.             symbols[symbol] = topics
  1621.  
  1622.     topics = {
  1623.         'TYPES': ('types', 'STRINGS UNICODE NUMBERS SEQUENCES MAPPINGS '
  1624.                   'FUNCTIONS CLASSES MODULES FILES inspect'),
  1625.         'STRINGS': ('strings', 'str UNICODE SEQUENCES STRINGMETHODS FORMATTING '
  1626.                     'TYPES'),
  1627.         'STRINGMETHODS': ('string-methods', 'STRINGS FORMATTING'),
  1628.         'FORMATTING': ('formatstrings', 'OPERATORS'),
  1629.         'UNICODE': ('strings', 'encodings unicode SEQUENCES STRINGMETHODS '
  1630.                     'FORMATTING TYPES'),
  1631.         'NUMBERS': ('numbers', 'INTEGER FLOAT COMPLEX TYPES'),
  1632.         'INTEGER': ('integers', 'int range'),
  1633.         'FLOAT': ('floating', 'float math'),
  1634.         'COMPLEX': ('imaginary', 'complex cmath'),
  1635.         'SEQUENCES': ('typesseq', 'STRINGMETHODS FORMATTING xrange LISTS'),
  1636.         'MAPPINGS': 'DICTIONARIES',
  1637.         'FUNCTIONS': ('typesfunctions', 'def TYPES'),
  1638.         'METHODS': ('typesmethods', 'class def CLASSES TYPES'),
  1639.         'CODEOBJECTS': ('bltin-code-objects', 'compile FUNCTIONS TYPES'),
  1640.         'TYPEOBJECTS': ('bltin-type-objects', 'types TYPES'),
  1641.         'FRAMEOBJECTS': 'TYPES',
  1642.         'TRACEBACKS': 'TYPES',
  1643.         'NONE': ('bltin-null-object', ''),
  1644.         'ELLIPSIS': ('bltin-ellipsis-object', 'SLICINGS'),
  1645.         'FILES': ('bltin-file-objects', ''),
  1646.         'SPECIALATTRIBUTES': ('specialattrs', ''),
  1647.         'CLASSES': ('types', 'class SPECIALMETHODS PRIVATENAMES'),
  1648.         'MODULES': ('typesmodules', 'import'),
  1649.         'PACKAGES': 'import',
  1650.         'EXPRESSIONS': ('operator-summary', 'lambda or and not in is BOOLEAN '
  1651.                         'COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER '
  1652.                         'UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES '
  1653.                         'LISTS DICTIONARIES BACKQUOTES'),
  1654.         'OPERATORS': 'EXPRESSIONS',
  1655.         'PRECEDENCE': 'EXPRESSIONS',
  1656.         'OBJECTS': ('objects', 'TYPES'),
  1657.         'SPECIALMETHODS': ('specialnames', 'BASICMETHODS ATTRIBUTEMETHODS '
  1658.                            'CALLABLEMETHODS SEQUENCEMETHODS1 MAPPINGMETHODS '
  1659.                            'SEQUENCEMETHODS2 NUMBERMETHODS CLASSES'),
  1660.         'BASICMETHODS': ('customization', 'cmp hash repr str SPECIALMETHODS'),
  1661.         'ATTRIBUTEMETHODS': ('attribute-access', 'ATTRIBUTES SPECIALMETHODS'),
  1662.         'CALLABLEMETHODS': ('callable-types', 'CALLS SPECIALMETHODS'),
  1663.         'SEQUENCEMETHODS1': ('sequence-types', 'SEQUENCES SEQUENCEMETHODS2 '
  1664.                              'SPECIALMETHODS'),
  1665.         'SEQUENCEMETHODS2': ('sequence-methods', 'SEQUENCES SEQUENCEMETHODS1 '
  1666.                              'SPECIALMETHODS'),
  1667.         'MAPPINGMETHODS': ('sequence-types', 'MAPPINGS SPECIALMETHODS'),
  1668.         'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
  1669.                           'SPECIALMETHODS'),
  1670.         'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
  1671.         'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
  1672.         'DYNAMICFEATURES': ('dynamic-features', ''),
  1673.         'SCOPING': 'NAMESPACES',
  1674.         'FRAMES': 'NAMESPACES',
  1675.         'EXCEPTIONS': ('exceptions', 'try except finally raise'),
  1676.         'COERCIONS': ('coercion-rules','CONVERSIONS'),
  1677.         'CONVERSIONS': ('conversions', 'COERCIONS'),
  1678.         'IDENTIFIERS': ('identifiers', 'keywords SPECIALIDENTIFIERS'),
  1679.         'SPECIALIDENTIFIERS': ('id-classes', ''),
  1680.         'PRIVATENAMES': ('atom-identifiers', ''),
  1681.         'LITERALS': ('atom-literals', 'STRINGS BACKQUOTES NUMBERS '
  1682.                      'TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'),
  1683.         'TUPLES': 'SEQUENCES',
  1684.         'TUPLELITERALS': ('exprlists', 'TUPLES LITERALS'),
  1685.         'LISTS': ('typesseq-mutable', 'LISTLITERALS'),
  1686.         'LISTLITERALS': ('lists', 'LISTS LITERALS'),
  1687.         'DICTIONARIES': ('typesmapping', 'DICTIONARYLITERALS'),
  1688.         'DICTIONARYLITERALS': ('dict', 'DICTIONARIES LITERALS'),
  1689.         'BACKQUOTES': ('string-conversions', 'repr str STRINGS LITERALS'),
  1690.         'ATTRIBUTES': ('attribute-references', 'getattr hasattr setattr '
  1691.                        'ATTRIBUTEMETHODS'),
  1692.         'SUBSCRIPTS': ('subscriptions', 'SEQUENCEMETHODS1'),
  1693.         'SLICINGS': ('slicings', 'SEQUENCEMETHODS2'),
  1694.         'CALLS': ('calls', 'EXPRESSIONS'),
  1695.         'POWER': ('power', 'EXPRESSIONS'),
  1696.         'UNARY': ('unary', 'EXPRESSIONS'),
  1697.         'BINARY': ('binary', 'EXPRESSIONS'),
  1698.         'SHIFTING': ('shifting', 'EXPRESSIONS'),
  1699.         'BITWISE': ('bitwise', 'EXPRESSIONS'),
  1700.         'COMPARISON': ('comparisons', 'EXPRESSIONS BASICMETHODS'),
  1701.         'BOOLEAN': ('booleans', 'EXPRESSIONS TRUTHVALUE'),
  1702.         'ASSERTION': 'assert',
  1703.         'ASSIGNMENT': ('assignment', 'AUGMENTEDASSIGNMENT'),
  1704.         'AUGMENTEDASSIGNMENT': ('augassign', 'NUMBERMETHODS'),
  1705.         'DELETION': 'del',
  1706.         'PRINTING': 'print',
  1707.         'RETURNING': 'return',
  1708.         'IMPORTING': 'import',
  1709.         'CONDITIONAL': 'if',
  1710.         'LOOPING': ('compound', 'for while break continue'),
  1711.         'TRUTHVALUE': ('truth', 'if while and or not BASICMETHODS'),
  1712.         'DEBUGGING': ('debugger', 'pdb'),
  1713.         'CONTEXTMANAGERS': ('context-managers', 'with'),
  1714.     }
  1715.  
  1716.     def __init__(self, input, output):
  1717.         self.input = input
  1718.         self.output = output
  1719.  
  1720.     def __repr__(self):
  1721.         if inspect.stack()[1][3] == '?':
  1722.             self()
  1723.             return ''
  1724.         return '<pydoc.Helper instance>'
  1725.  
  1726.     def __call__(self, request=None):
  1727.         if request is not None:
  1728.             self.help(request)
  1729.         else:
  1730.             self.intro()
  1731.             self.interact()
  1732.             self.output.write('''
  1733. You are now leaving help and returning to the Python interpreter.
  1734. If you want to ask for help on a particular object directly from the
  1735. interpreter, you can type "help(object)".  Executing "help('string')"
  1736. has the same effect as typing a particular string at the help> prompt.
  1737. ''')
  1738.  
  1739.     def interact(self):
  1740.         self.output.write('\n')
  1741.         while True:
  1742.             try:
  1743.                 request = self.getline('help> ')
  1744.                 if not request: break
  1745.             except (KeyboardInterrupt, EOFError):
  1746.                 break
  1747.             request = strip(replace(request, '"', '', "'", ''))
  1748.             if lower(request) in ('q', 'quit'): break
  1749.             self.help(request)
  1750.  
  1751.     def getline(self, prompt):
  1752.         """Read one line, using raw_input when available."""
  1753.         if self.input is sys.stdin:
  1754.             return raw_input(prompt)
  1755.         else:
  1756.             self.output.write(prompt)
  1757.             self.output.flush()
  1758.             return self.input.readline()
  1759.  
  1760.     def help(self, request):
  1761.         if type(request) is type(''):
  1762.             request = request.strip()
  1763.             if request == 'help': self.intro()
  1764.             elif request == 'keywords': self.listkeywords()
  1765.             elif request == 'symbols': self.listsymbols()
  1766.             elif request == 'topics': self.listtopics()
  1767.             elif request == 'modules': self.listmodules()
  1768.             elif request[:8] == 'modules ':
  1769.                 self.listmodules(split(request)[1])
  1770.             elif request in self.symbols: self.showsymbol(request)
  1771.             elif request in self.keywords: self.showtopic(request)
  1772.             elif request in self.topics: self.showtopic(request)
  1773.             elif request: doc(request, 'Help on %s:')
  1774.         elif isinstance(request, Helper): self()
  1775.         else: doc(request, 'Help on %s:')
  1776.         self.output.write('\n')
  1777.  
  1778.     def intro(self):
  1779.         self.output.write('''
  1780. Welcome to Python %s!  This is the online help utility.
  1781.  
  1782. If this is your first time using Python, you should definitely check out
  1783. the tutorial on the Internet at http://docs.python.org/tutorial/.
  1784.  
  1785. Enter the name of any module, keyword, or topic to get help on writing
  1786. Python programs and using Python modules.  To quit this help utility and
  1787. return to the interpreter, just type "quit".
  1788.  
  1789. To get a list of available modules, keywords, or topics, type "modules",
  1790. "keywords", or "topics".  Each module also comes with a one-line summary
  1791. of what it does; to list the modules whose summaries contain a given word
  1792. such as "spam", type "modules spam".
  1793. ''' % sys.version[:3])
  1794.  
  1795.     def list(self, items, columns=4, width=80):
  1796.         items = items[:]
  1797.         items.sort()
  1798.         colw = width / columns
  1799.         rows = (len(items) + columns - 1) / columns
  1800.         for row in range(rows):
  1801.             for col in range(columns):
  1802.                 i = col * rows + row
  1803.                 if i < len(items):
  1804.                     self.output.write(items[i])
  1805.                     if col < columns - 1:
  1806.                         self.output.write(' ' + ' ' * (colw-1 - len(items[i])))
  1807.             self.output.write('\n')
  1808.  
  1809.     def listkeywords(self):
  1810.         self.output.write('''
  1811. Here is a list of the Python keywords.  Enter any keyword to get more help.
  1812.  
  1813. ''')
  1814.         self.list(self.keywords.keys())
  1815.  
  1816.     def listsymbols(self):
  1817.         self.output.write('''
  1818. Here is a list of the punctuation symbols which Python assigns special meaning
  1819. to. Enter any symbol to get more help.
  1820.  
  1821. ''')
  1822.         self.list(self.symbols.keys())
  1823.  
  1824.     def listtopics(self):
  1825.         self.output.write('''
  1826. Here is a list of available topics.  Enter any topic name to get more help.
  1827.  
  1828. ''')
  1829.         self.list(self.topics.keys())
  1830.  
  1831.     def showtopic(self, topic, more_xrefs=''):
  1832.         try:
  1833.             import pydoc_topics
  1834.         except ImportError:
  1835.             self.output.write('''
  1836. Sorry, topic and keyword documentation is not available because the
  1837. module "pydoc_topics" could not be found.
  1838. ''')
  1839.             return
  1840.         target = self.topics.get(topic, self.keywords.get(topic))
  1841.         if not target:
  1842.             self.output.write('no documentation found for %s\n' % repr(topic))
  1843.             return
  1844.         if type(target) is type(''):
  1845.             return self.showtopic(target, more_xrefs)
  1846.  
  1847.         label, xrefs = target
  1848.         try:
  1849.             doc = pydoc_topics.topics[label]
  1850.         except KeyError:
  1851.             self.output.write('no documentation found for %s\n' % repr(topic))
  1852.             return
  1853.         pager(strip(doc) + '\n')
  1854.         if more_xrefs:
  1855.             xrefs = (xrefs or '') + ' ' + more_xrefs
  1856.         if xrefs:
  1857.             import StringIO, formatter
  1858.             buffer = StringIO.StringIO()
  1859.             formatter.DumbWriter(buffer).send_flowing_data(
  1860.                 'Related help topics: ' + join(split(xrefs), ', ') + '\n')
  1861.             self.output.write('\n%s\n' % buffer.getvalue())
  1862.  
  1863.     def showsymbol(self, symbol):
  1864.         target = self.symbols[symbol]
  1865.         topic, _, xrefs = target.partition(' ')
  1866.         self.showtopic(topic, xrefs)
  1867.  
  1868.     def listmodules(self, key=''):
  1869.         if key:
  1870.             self.output.write('''
  1871. Here is a list of matching modules.  Enter any module name to get more help.
  1872.  
  1873. ''')
  1874.             apropos(key)
  1875.         else:
  1876.             self.output.write('''
  1877. Please wait a moment while I gather a list of all available modules...
  1878.  
  1879. ''')
  1880.             modules = {}
  1881.             def callback(path, modname, desc, modules=modules):
  1882.                 if modname and modname[-9:] == '.__init__':
  1883.                     modname = modname[:-9] + ' (package)'
  1884.                 if find(modname, '.') < 0:
  1885.                     modules[modname] = 1
  1886.             def onerror(modname):
  1887.                 callback(None, modname, None)
  1888.             ModuleScanner().run(callback, onerror=onerror)
  1889.             self.list(modules.keys())
  1890.             self.output.write('''
  1891. Enter any module name to get more help.  Or, type "modules spam" to search
  1892. for modules whose descriptions contain the word "spam".
  1893. ''')
  1894.  
  1895. help = Helper(sys.stdin, sys.stdout)
  1896.  
  1897. class Scanner:
  1898.     """A generic tree iterator."""
  1899.     def __init__(self, roots, children, descendp):
  1900.         self.roots = roots[:]
  1901.         self.state = []
  1902.         self.children = children
  1903.         self.descendp = descendp
  1904.  
  1905.     def next(self):
  1906.         if not self.state:
  1907.             if not self.roots:
  1908.                 return None
  1909.             root = self.roots.pop(0)
  1910.             self.state = [(root, self.children(root))]
  1911.         node, children = self.state[-1]
  1912.         if not children:
  1913.             self.state.pop()
  1914.             return self.next()
  1915.         child = children.pop(0)
  1916.         if self.descendp(child):
  1917.             self.state.append((child, self.children(child)))
  1918.         return child
  1919.  
  1920.  
  1921. class ModuleScanner:
  1922.     """An interruptible scanner that searches module synopses."""
  1923.  
  1924.     def run(self, callback, key=None, completer=None, onerror=None):
  1925.         if key: key = lower(key)
  1926.         self.quit = False
  1927.         seen = {}
  1928.  
  1929.         for modname in sys.builtin_module_names:
  1930.             if modname != '__main__':
  1931.                 seen[modname] = 1
  1932.                 if key is None:
  1933.                     callback(None, modname, '')
  1934.                 else:
  1935.                     desc = split(__import__(modname).__doc__ or '', '\n')[0]
  1936.                     if find(lower(modname + ' - ' + desc), key) >= 0:
  1937.                         callback(None, modname, desc)
  1938.  
  1939.         for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
  1940.             if self.quit:
  1941.                 break
  1942.             if key is None:
  1943.                 callback(None, modname, '')
  1944.             else:
  1945.                 loader = importer.find_module(modname)
  1946.                 if hasattr(loader,'get_source'):
  1947.                     import StringIO
  1948.                     desc = source_synopsis(
  1949.                         StringIO.StringIO(loader.get_source(modname))
  1950.                     ) or ''
  1951.                     if hasattr(loader,'get_filename'):
  1952.                         path = loader.get_filename(modname)
  1953.                     else:
  1954.                         path = None
  1955.                 else:
  1956.                     module = loader.load_module(modname)
  1957.                     desc = (module.__doc__ or '').splitlines()[0]
  1958.                     path = getattr(module,'__file__',None)
  1959.                 if find(lower(modname + ' - ' + desc), key) >= 0:
  1960.                     callback(path, modname, desc)
  1961.  
  1962.         if completer:
  1963.             completer()
  1964.  
  1965. def apropos(key):
  1966.     """Print all the one-line module summaries that contain a substring."""
  1967.     def callback(path, modname, desc):
  1968.         if modname[-9:] == '.__init__':
  1969.             modname = modname[:-9] + ' (package)'
  1970.         print modname, desc and '- ' + desc
  1971.     try: import warnings
  1972.     except ImportError: pass
  1973.     else: warnings.filterwarnings('ignore') # ignore problems during import
  1974.     ModuleScanner().run(callback, key)
  1975.  
  1976. # --------------------------------------------------- web browser interface
  1977.  
  1978. def serve(port, callback=None, completer=None):
  1979.     import BaseHTTPServer, mimetools, select
  1980.  
  1981.     # Patch up mimetools.Message so it doesn't break if rfc822 is reloaded.
  1982.     class Message(mimetools.Message):
  1983.         def __init__(self, fp, seekable=1):
  1984.             Message = self.__class__
  1985.             Message.__bases__[0].__bases__[0].__init__(self, fp, seekable)
  1986.             self.encodingheader = self.getheader('content-transfer-encoding')
  1987.             self.typeheader = self.getheader('content-type')
  1988.             self.parsetype()
  1989.             self.parseplist()
  1990.  
  1991.     class DocHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  1992.         def send_document(self, title, contents):
  1993.             try:
  1994.                 self.send_response(200)
  1995.                 self.send_header('Content-Type', 'text/html')
  1996.                 self.end_headers()
  1997.                 self.wfile.write(html.page(title, contents))
  1998.             except IOError: pass
  1999.  
  2000.         def do_GET(self):
  2001.             path = self.path
  2002.             if path[-5:] == '.html': path = path[:-5]
  2003.             if path[:1] == '/': path = path[1:]
  2004.             if path and path != '.':
  2005.                 try:
  2006.                     obj = locate(path, forceload=1)
  2007.                 except ErrorDuringImport, value:
  2008.                     self.send_document(path, html.escape(str(value)))
  2009.                     return
  2010.                 if obj:
  2011.                     self.send_document(describe(obj), html.document(obj, path))
  2012.                 else:
  2013.                     self.send_document(path,
  2014. 'no Python documentation found for %s' % repr(path))
  2015.             else:
  2016.                 heading = html.heading(
  2017. '<big><big><strong>Python: Index of Modules</strong></big></big>',
  2018. '#ffffff', '#7799ee')
  2019.                 def bltinlink(name):
  2020.                     return '<a href="%s.html">%s</a>' % (name, name)
  2021.                 names = filter(lambda x: x != '__main__',
  2022.                                sys.builtin_module_names)
  2023.                 contents = html.multicolumn(names, bltinlink)
  2024.                 indices = ['<p>' + html.bigsection(
  2025.                     'Built-in Modules', '#ffffff', '#ee77aa', contents)]
  2026.  
  2027.                 seen = {}
  2028.                 for dir in sys.path:
  2029.                     indices.append(html.index(dir, seen))
  2030.                 contents = heading + join(indices) + '''<p align=right>
  2031. <font color="#909090" face="helvetica, arial"><strong>
  2032. pydoc</strong> by Ka-Ping Yee <ping@lfw.org></font>'''
  2033.                 self.send_document('Index of Modules', contents)
  2034.  
  2035.         def log_message(self, *args): pass
  2036.  
  2037.     class DocServer(BaseHTTPServer.HTTPServer):
  2038.         def __init__(self, port, callback):
  2039.             host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
  2040.             self.address = ('', port)
  2041.             self.url = 'http://%s:%d/' % (host, port)
  2042.             self.callback = callback
  2043.             self.base.__init__(self, self.address, self.handler)
  2044.  
  2045.         def serve_until_quit(self):
  2046.             import select
  2047.             self.quit = False
  2048.             while not self.quit:
  2049.                 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
  2050.                 if rd: self.handle_request()
  2051.  
  2052.         def server_activate(self):
  2053.             self.base.server_activate(self)
  2054.             if self.callback: self.callback(self)
  2055.  
  2056.     DocServer.base = BaseHTTPServer.HTTPServer
  2057.     DocServer.handler = DocHandler
  2058.     DocHandler.MessageClass = Message
  2059.     try:
  2060.         try:
  2061.             DocServer(port, callback).serve_until_quit()
  2062.         except (KeyboardInterrupt, select.error):
  2063.             pass
  2064.     finally:
  2065.         if completer: completer()
  2066.  
  2067. # ----------------------------------------------------- graphical interface
  2068.  
  2069. def gui():
  2070.     """Graphical interface (starts web server and pops up a control window)."""
  2071.     class GUI:
  2072.         def __init__(self, window, port=7464):
  2073.             self.window = window
  2074.             self.server = None
  2075.             self.scanner = None
  2076.  
  2077.             import Tkinter
  2078.             self.server_frm = Tkinter.Frame(window)
  2079.             self.title_lbl = Tkinter.Label(self.server_frm,
  2080.                 text='Starting server...\n ')
  2081.             self.open_btn = Tkinter.Button(self.server_frm,
  2082.                 text='open browser', command=self.open, state='disabled')
  2083.             self.quit_btn = Tkinter.Button(self.server_frm,
  2084.                 text='quit serving', command=self.quit, state='disabled')
  2085.  
  2086.             self.search_frm = Tkinter.Frame(window)
  2087.             self.search_lbl = Tkinter.Label(self.search_frm, text='Search for')
  2088.             self.search_ent = Tkinter.Entry(self.search_frm)
  2089.             self.search_ent.bind('<Return>', self.search)
  2090.             self.stop_btn = Tkinter.Button(self.search_frm,
  2091.                 text='stop', pady=0, command=self.stop, state='disabled')
  2092.             if sys.platform == 'win32':
  2093.                 # Trying to hide and show this button crashes under Windows.
  2094.                 self.stop_btn.pack(side='right')
  2095.  
  2096.             self.window.title('pydoc')
  2097.             self.window.protocol('WM_DELETE_WINDOW', self.quit)
  2098.             self.title_lbl.pack(side='top', fill='x')
  2099.             self.open_btn.pack(side='left', fill='x', expand=1)
  2100.             self.quit_btn.pack(side='right', fill='x', expand=1)
  2101.             self.server_frm.pack(side='top', fill='x')
  2102.  
  2103.             self.search_lbl.pack(side='left')
  2104.             self.search_ent.pack(side='right', fill='x', expand=1)
  2105.             self.search_frm.pack(side='top', fill='x')
  2106.             self.search_ent.focus_set()
  2107.  
  2108.             font = ('helvetica', sys.platform == 'win32' and 8 or 10)
  2109.             self.result_lst = Tkinter.Listbox(window, font=font, height=6)
  2110.             self.result_lst.bind('<Button-1>', self.select)
  2111.             self.result_lst.bind('<Double-Button-1>', self.goto)
  2112.             self.result_scr = Tkinter.Scrollbar(window,
  2113.                 orient='vertical', command=self.result_lst.yview)
  2114.             self.result_lst.config(yscrollcommand=self.result_scr.set)
  2115.  
  2116.             self.result_frm = Tkinter.Frame(window)
  2117.             self.goto_btn = Tkinter.Button(self.result_frm,
  2118.                 text='go to selected', command=self.goto)
  2119.             self.hide_btn = Tkinter.Button(self.result_frm,
  2120.                 text='hide results', command=self.hide)
  2121.             self.goto_btn.pack(side='left', fill='x', expand=1)
  2122.             self.hide_btn.pack(side='right', fill='x', expand=1)
  2123.  
  2124.             self.window.update()
  2125.             self.minwidth = self.window.winfo_width()
  2126.             self.minheight = self.window.winfo_height()
  2127.             self.bigminheight = (self.server_frm.winfo_reqheight() +
  2128.                                  self.search_frm.winfo_reqheight() +
  2129.                                  self.result_lst.winfo_reqheight() +
  2130.                                  self.result_frm.winfo_reqheight())
  2131.             self.bigwidth, self.bigheight = self.minwidth, self.bigminheight
  2132.             self.expanded = 0
  2133.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2134.             self.window.wm_minsize(self.minwidth, self.minheight)
  2135.             self.window.tk.willdispatch()
  2136.  
  2137.             import threading
  2138.             threading.Thread(
  2139.                 target=serve, args=(port, self.ready, self.quit)).start()
  2140.  
  2141.         def ready(self, server):
  2142.             self.server = server
  2143.             self.title_lbl.config(
  2144.                 text='Python documentation server at\n' + server.url)
  2145.             self.open_btn.config(state='normal')
  2146.             self.quit_btn.config(state='normal')
  2147.  
  2148.         def open(self, event=None, url=None):
  2149.             url = url or self.server.url
  2150.             try:
  2151.                 import webbrowser
  2152.                 webbrowser.open(url)
  2153.             except ImportError: # pre-webbrowser.py compatibility
  2154.                 if sys.platform == 'win32':
  2155.                     os.system('start "%s"' % url)
  2156.                 elif sys.platform == 'mac':
  2157.                     try: import ic
  2158.                     except ImportError: pass
  2159.                     else: ic.launchurl(url)
  2160.                 else:
  2161.                     rc = os.system('netscape -remote "openURL(%s)" &' % url)
  2162.                     if rc: os.system('netscape "%s" &' % url)
  2163.  
  2164.         def quit(self, event=None):
  2165.             if self.server:
  2166.                 self.server.quit = 1
  2167.             self.window.quit()
  2168.  
  2169.         def search(self, event=None):
  2170.             key = self.search_ent.get()
  2171.             self.stop_btn.pack(side='right')
  2172.             self.stop_btn.config(state='normal')
  2173.             self.search_lbl.config(text='Searching for "%s"...' % key)
  2174.             self.search_ent.forget()
  2175.             self.search_lbl.pack(side='left')
  2176.             self.result_lst.delete(0, 'end')
  2177.             self.goto_btn.config(state='disabled')
  2178.             self.expand()
  2179.  
  2180.             import threading
  2181.             if self.scanner:
  2182.                 self.scanner.quit = 1
  2183.             self.scanner = ModuleScanner()
  2184.             threading.Thread(target=self.scanner.run,
  2185.                              args=(self.update, key, self.done)).start()
  2186.  
  2187.         def update(self, path, modname, desc):
  2188.             if modname[-9:] == '.__init__':
  2189.                 modname = modname[:-9] + ' (package)'
  2190.             self.result_lst.insert('end',
  2191.                 modname + ' - ' + (desc or '(no description)'))
  2192.  
  2193.         def stop(self, event=None):
  2194.             if self.scanner:
  2195.                 self.scanner.quit = 1
  2196.                 self.scanner = None
  2197.  
  2198.         def done(self):
  2199.             self.scanner = None
  2200.             self.search_lbl.config(text='Search for')
  2201.             self.search_lbl.pack(side='left')
  2202.             self.search_ent.pack(side='right', fill='x', expand=1)
  2203.             if sys.platform != 'win32': self.stop_btn.forget()
  2204.             self.stop_btn.config(state='disabled')
  2205.  
  2206.         def select(self, event=None):
  2207.             self.goto_btn.config(state='normal')
  2208.  
  2209.         def goto(self, event=None):
  2210.             selection = self.result_lst.curselection()
  2211.             if selection:
  2212.                 modname = split(self.result_lst.get(selection[0]))[0]
  2213.                 self.open(url=self.server.url + modname + '.html')
  2214.  
  2215.         def collapse(self):
  2216.             if not self.expanded: return
  2217.             self.result_frm.forget()
  2218.             self.result_scr.forget()
  2219.             self.result_lst.forget()
  2220.             self.bigwidth = self.window.winfo_width()
  2221.             self.bigheight = self.window.winfo_height()
  2222.             self.window.wm_geometry('%dx%d' % (self.minwidth, self.minheight))
  2223.             self.window.wm_minsize(self.minwidth, self.minheight)
  2224.             self.expanded = 0
  2225.  
  2226.         def expand(self):
  2227.             if self.expanded: return
  2228.             self.result_frm.pack(side='bottom', fill='x')
  2229.             self.result_scr.pack(side='right', fill='y')
  2230.             self.result_lst.pack(side='top', fill='both', expand=1)
  2231.             self.window.wm_geometry('%dx%d' % (self.bigwidth, self.bigheight))
  2232.             self.window.wm_minsize(self.minwidth, self.bigminheight)
  2233.             self.expanded = 1
  2234.  
  2235.         def hide(self, event=None):
  2236.             self.stop()
  2237.             self.collapse()
  2238.  
  2239.     import Tkinter
  2240.     try:
  2241.         root = Tkinter.Tk()
  2242.         # Tk will crash if pythonw.exe has an XP .manifest
  2243.         # file and the root has is not destroyed explicitly.
  2244.         # If the problem is ever fixed in Tk, the explicit
  2245.         # destroy can go.
  2246.         try:
  2247.             gui = GUI(root)
  2248.             root.mainloop()
  2249.         finally:
  2250.             root.destroy()
  2251.     except KeyboardInterrupt:
  2252.         pass
  2253.  
  2254. # -------------------------------------------------- command-line interface
  2255.  
  2256. def ispath(x):
  2257.     return isinstance(x, str) and find(x, os.sep) >= 0
  2258.  
  2259. def cli():
  2260.     """Command-line interface (looks at sys.argv to decide what to do)."""
  2261.     import getopt
  2262.     class BadUsage: pass
  2263.  
  2264.     # Scripts don't get the current directory in their path by default.
  2265.     scriptdir = os.path.dirname(sys.argv[0])
  2266.     if scriptdir in sys.path:
  2267.         sys.path.remove(scriptdir)
  2268.     sys.path.insert(0, '.')
  2269.  
  2270.     try:
  2271.         opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
  2272.         writing = 0
  2273.  
  2274.         for opt, val in opts:
  2275.             if opt == '-g':
  2276.                 gui()
  2277.                 return
  2278.             if opt == '-k':
  2279.                 apropos(val)
  2280.                 return
  2281.             if opt == '-p':
  2282.                 try:
  2283.                     port = int(val)
  2284.                 except ValueError:
  2285.                     raise BadUsage
  2286.                 def ready(server):
  2287.                     print 'pydoc server ready at %s' % server.url
  2288.                 def stopped():
  2289.                     print 'pydoc server stopped'
  2290.                 serve(port, ready, stopped)
  2291.                 return
  2292.             if opt == '-w':
  2293.                 writing = 1
  2294.  
  2295.         if not args: raise BadUsage
  2296.         for arg in args:
  2297.             if ispath(arg) and not os.path.exists(arg):
  2298.                 print 'file %r does not exist' % arg
  2299.                 break
  2300.             try:
  2301.                 if ispath(arg) and os.path.isfile(arg):
  2302.                     arg = importfile(arg)
  2303.                 if writing:
  2304.                     if ispath(arg) and os.path.isdir(arg):
  2305.                         writedocs(arg)
  2306.                     else:
  2307.                         writedoc(arg)
  2308.                 else:
  2309.                     help.help(arg)
  2310.             except ErrorDuringImport, value:
  2311.                 print value
  2312.  
  2313.     except (getopt.error, BadUsage):
  2314.         cmd = os.path.basename(sys.argv[0])
  2315.         print """pydoc - the Python documentation tool
  2316.  
  2317. %s <name> ...
  2318.     Show text documentation on something.  <name> may be the name of a
  2319.     Python keyword, topic, function, module, or package, or a dotted
  2320.     reference to a class or function within a module or module in a
  2321.     package.  If <name> contains a '%s', it is used as the path to a
  2322.     Python source file to document. If name is 'keywords', 'topics',
  2323.     or 'modules', a listing of these things is displayed.
  2324.  
  2325. %s -k <keyword>
  2326.     Search for a keyword in the synopsis lines of all available modules.
  2327.  
  2328. %s -p <port>
  2329.     Start an HTTP server on the given port on the local machine.
  2330.  
  2331. %s -g
  2332.     Pop up a graphical interface for finding and serving documentation.
  2333.  
  2334. %s -w <name> ...
  2335.     Write out the HTML documentation for a module to a file in the current
  2336.     directory.  If <name> contains a '%s', it is treated as a filename; if
  2337.     it names a directory, documentation is written for all the contents.
  2338. """ % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
  2339.  
  2340. if __name__ == '__main__': cli()
  2341.